<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container" />
      <div class="login-main">
        <div class="login-title">
          欢迎使用——三宝金山中台
        </div>
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="login" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="off"
            @change="getCompany"
          />
        </el-form-item>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="passwordline" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            auto-complete="off"
            @keyup.enter.native="handleLogin"
          />
          <span
            class="show-pwd"
            @click="showPwd"
          >
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
        <el-button
          :disabled="!isLogin"
          :loading="loginLoading"
          type="primary"
          style="width: 100%; margin-top:38px; margin-bottom: 0;"
          @click.native.prevent="handleLogin"
        >
          {{ loginText }}
        </el-button>
        <div class="edition">
          当前版本：v1.3.9
        </div>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts">
import { Component, Watch, Vue, Ref } from 'vue-property-decorator'
import { Input, Form } from 'element-ui'
import { randomLenNum } from '@/utils/index'
import { UserModule } from '@/store/modules/user'
import { TagsViewModule } from '@/store/modules/tags-view'
import { PermissionModule } from '@/store/modules/permission'
// import {mapGetters, mapState} from 'vuex'
// 获取 企业列表
import { getCompanyList } from '@/api/user'
// import {Route} from 'vue-router'
// import {number} from '@/utils/rules'
// import { mapActions } from 'vuex'
@Component
export default class Login extends Vue {
  name = 'Login'
  loginText = '登 录'
  loginLoading = false
  loginForm = {
    code: '',
    username: '',
    password: '',
    randomStr: '',
    platform: '1',
    TENANT_ID: 0
  }
  code = {
    src: '/admin/code',
    value: '',
    len: 4,
    type: 'image'
  }
  loginRules = {
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度最少为6位', trigger: 'blur' }
    ],
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
    // TENANT_ID: [
    //   { required: true, message: '请选择所属企业', trigger: 'change' }
    // ]
  }
  passwordType = 'password'
  // redirect = ''
  companyTypes: any[] = []

  /* watch: {
    '$route': {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  }, */

  /* @Watch('$route', {immediate: true})
  onChangeRoute(route: Route) {
    this.redirect = route.query && route.query.redirect
  } */

  @Ref('username') readonly refUserName!: Input
  @Ref('password') readonly refPassword!: Input
  @Ref('loginForm') readonly refLoginForm!: Form

  get redirect() {
    return this.$route.query.redirect as string
  }

  // 可以登录
  get isLogin():boolean {
    return !!(this.companyTypes.length > 0 && this.loginForm.password.length > 0)
  }

  created() {
    // this.$router.replace('/login')
    this.refreshCode()
  }

  mounted() {
    this.refUserName.focus()
    TagsViewModule.delAllViews()
    PermissionModule.removeRoutes()
    UserModule.ResetToken()
  }

  public searchCompany() {
    if (this.loginForm.username) {
      this.getCompany(this.loginForm.username)
    }
  }

  public getCompany(name: string) {
    getCompanyList(name).then((res: any) => {
      if (res.code === 1 && res.data.length > 0) {
        this.companyTypes = res.data
      } else {
        this.companyTypes = []
        this.$message({
          message: '用戶名不存在',
          type: 'error',
          duration: 5 * 1000
        })
      }
    })
  }

  public refreshCode() {
    this.loginForm.code = ''
    this.loginForm.randomStr = randomLenNum(this.code.len, 0)
    this.code.type === 'text'
      ? (this.code.value = randomLenNum(this.code.len))
      : (this.code.src = 'admin/code/' + this.loginForm.randomStr)
  }

  public showPwd() {
    if (this.passwordType === 'password') {
      this.passwordType = ''
    } else {
      this.passwordType = 'password'
    }
    this.$nextTick(() => {
      this.refPassword.focus()
    })
  }

  public handleLogin() {
    this.refLoginForm.validate(valid => {
      if (valid) {
        this.loginText = '登录中'
        this.loginLoading = true
        if (this.companyTypes.length > 0) {
          this.loginForm.TENANT_ID = this.companyTypes[0].tenantId || 0
          UserModule.LoginByUsername(this.loginForm).then(res => {
            this.$router.push({
              path: this.$route.query.redirect as string || '/'
            }).then(_ => {
              // location.reload()
            })
          }).catch(error => {
            console.log('login->', error)
            this.loginText = '登录'
            this.loginLoading = false
            this.refreshCode()
          })
        }
      }
    })
  }
}
</script>
<style scoped>
  .edition {
    margin-top: 20px;
    color: #999999;
    font-size: 14px;
  }
</style>
